package com.ykefu.assign.netty.netty;

import com.ykefu.assign.netty.netty.websocket.ChannelManager;
import com.ykefu.assign.netty.netty.websocket.HandlerConnect;
import com.ykefu.assign.netty.netty.websocket.HandlerMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Locale;

/**
 * @author likai
 * @date 2020/4/17 9:07
 * @email likai@7moor..com
 * @desc
 */
public class NettyWebSocketProtocolHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private static final Logger LOGGER = LoggerFactory.getLogger(NettyWebSocketProtocolHandler.class);



    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
        if (msg instanceof TextWebSocketFrame) {
            // Send the uppercase string back.
            String request = ((TextWebSocketFrame) msg).text();
            LOGGER.info("socket 接受客户端消息：{}",request);
            HandlerMessage.getInstance().sendToAll(request);
        }else if(msg instanceof CloseWebSocketFrame){
            LOGGER.info("断开连接：{}");
        } else if(msg instanceof PingWebSocketFrame){
            LOGGER.info("ping ");
        }else {
            String message = "unsupported frame type: " + msg.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE.name().equals(evt.toString())) {
            HandlerConnect.getInstance().connect(ctx);
        }
        if(WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_ISSUED.name().equals(evt.toString())){
            LOGGER.error("socket 连接有问题，服务器未响应");
        }
        if(WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_TIMEOUT.name().equals(evt.toString())){
            LOGGER.error("socket 握手超时");
        }
        super.userEventTriggered(ctx, evt);
    }
}
